/*
 * UpdateSolver.cpp
 *
 *  Created on: 2021年8月11日
 *      Author: Administrator
 */

#include "UpdateSolver.h"
#include <utils/Log.h>
#include <json/json.h>
#include <base/time.hpp>
#include <base/strings.hpp>
#include <base/sematic_version.hpp>
#include <thread>
#include "zkota/version.h"
#include <base/files.hpp>
#include <os/UpgradeMonitor.h>

#define SHELL(program) if (system(program)) {}

void startCheckNewVersion(const std::string& app_name,
    const VersionCallback& callback) {

  std::thread backend([app_name, callback]() {
    GrowServer grow;
    try {
      auto info = grow.latestVersion(app_name);
      if (!callback) {
        return;
      }
      base::SematicVersion local(APP_VERSION);
      base::SematicVersion remote;
      if(!remote.parse(info.version)) {
        LOGE("invalid remote sematic version '%s'", info.version.c_str());
        info.is_newer = true;
        callback(info);
        return;
      }
      LOGD("remote version %s", remote.toString().c_str());
      LOGD("local version %s", local.toString().c_str());
      if (local >= remote) {
		  info.is_newer = false;
		  LOGD("local version newer");
      }else{
    	  info.is_newer = true;
      }
      callback(info);
    } catch (std::exception& e) {
      LOGE("check version info error: %s", e.what());
    }
  });
  backend.detach();
}

void updateProcessing(const http::HTTPClient::ProgressCallback& progress) {
  GrowServer grow;
  auto info = grow.latestVersion(APP_GROW_NAME);
  http::HTTPClient client;
  client.setConnectTimeout(5000);
  client.setLowSpeedLimit(1024, 5);
  http::HTTPRequest request("GET", info.url);
  std::string target = "/tmp/update.img";
  auto temp = target + ".downloading";
  auto response = client.perform(request, temp, progress);
  if (response.status() != 200) {
    throw std::runtime_error("下载失败");
  }
  if (base::file_size(temp) != info.file_size) {
    throw std::runtime_error("文件校验失败");
  }
  auto dir = base::path::dir(target);
  remove(target.c_str());
  rename(temp.c_str(), target.c_str());
  SHELL(base::format("echo 0 > %s/zkautoupgrade", dir.c_str()).c_str());
  UPGRADEMONITOR->checkUpgradeFile(dir.c_str());
}
